package com.kantboot.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kantboot.user.entity.CesUser;
import com.kantboot.user.entity.CesWechatUser;
import com.kantboot.user.mapper.CesUserMapper;
import com.kantboot.user.mapper.CesWechatUserMapper;
import com.kantboot.user.service.CesWechatUserService;
import com.kantboot.user.vo.CesUserVO;
import com.kantboot.wechat.applet.entity.AppletUserInfoEntity;
import com.kantboot.wechat.applet.entity.AppletUserInfoEntity.Param;
import com.kantboot.wechat.applet.entity.AppletUserInfoEntity.PhoneNumberResult;
import com.kantboot.wechat.applet.entity.AuthCode2SessionEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2021-08-12
 */
@Service
public class CesWechatUserServiceImpl extends ServiceImpl<CesWechatUserMapper, CesWechatUser> implements CesWechatUserService {

    @Resource
    CesWechatUserMapper cesWechatUserMapper;
    @Resource
    CesUserMapper cesUserMapper;
    @Resource
    AppletUserInfoEntity appletUserInfoEntity;


    @Override
    public CesUser login(CesUserVO cesUserVO) {
        PhoneNumberResult phoneNumberResult = appletUserInfoEntity.decryptPhoneNumberResult(
                new Param()
                        .setEncryptedData(cesUserVO.getEncryptedData())
                        .setIv(cesUserVO.getIv())
                        .setCode(cesUserVO.getCode())
        );

        //判断账号是否已存在
        List<CesWechatUser> cesWechatUserList = cesWechatUserMapper.selectList(
                new QueryWrapper<CesWechatUser>().eq(
                        "openid", phoneNumberResult.getOpenId()
                )
        );

        if(cesWechatUserList.size()==0){
            CesUser cesUser=new CesUser()
                    .setNickname(cesUserVO.getNickname())
                    .setPhoneNumber(cesUserVO.getPhoneNumber());

            cesUserMapper.insert(cesUser);

            CesWechatUser cesWechatUserByInsert=new CesWechatUser()
                    .setUnionid(phoneNumberResult.getUnionid())
                    .setOpenid(phoneNumberResult.getOpenId())
                    .setUserId(cesUser.getId());

            cesWechatUserMapper.insert(cesWechatUserByInsert);

        }

        CesWechatUser cesWechatUser = cesWechatUserMapper.selectOne(
                new QueryWrapper<CesWechatUser>().eq(
                        "openid", phoneNumberResult.getOpenId()
                )
        );
        return cesUserMapper.selectById(cesWechatUser.getUserId());

    }

}
